#include <stdio.h>
#include <stdlib.h>

//栈元素表示
typedef int ElementType;
typedef struct StackNode {
    ElementType data;
    struct StackNode *next;
} StackNode;

// 创建栈顶元素
StackNode* createNode(ElementType data) {
    StackNode *newNode = (StackNode *)malloc(sizeof(StackNode));
    if (newNode == NULL) {
        printf("Memory allocation failed for stack node.\n");
        exit(1);
    }
    newNode->data = data;
    newNode->next = NULL;
    return newNode;
}

// 入栈
void push(StackNode **top, ElementType newData) {
    StackNode* newNode = createNode(newData);
    if (newNode == NULL) {
        return;
    }
    newNode->next = *top;
    *top = newNode;
}

// 出栈
ElementType pop(StackNode **top) {
    if (*top == NULL) {
        printf("栈为空，无法出栈\n");
        exit(1);
    }
    int data = (*top)->data;
    *top = (*top)->next;
    return data;
}




int main(void) {
    // 栈底指针
    StackNode *top = NULL;
    // 入栈操作
    push(&top, 1);
    push(&top, 2);
    push(&top, 3);
    push(&top, 4);

    // 出栈操作
    printf("出栈元素: %d\n", pop(&top)); // 4
    printf("出栈元素: %d\n", pop(&top)); // 3

    return 0;
}